package timing.ukulele.portal.api;

import timing.ukulele.portal.persistent.User;
import timing.ukulele.portal.service.UserService;
import timing.ukulele.common.ResponseResult;
import timing.ukulele.common.portal.UserData;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/user")
public class UserApi {
    private final UserService userService;

    public UserApi(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/findByUsername")
    public ResponseResult<UserData> findByUsername(@RequestParam("username") String username) {
        final User user = this.userService.getByUsername(username);
        if (user != null) {
            UserData data = new UserData();
            BeanUtils.copyProperties(user, data);
            if (data.getRoleId() != 1){
                List<Long> systemIds = userService.getBaseMapper().getSystemIdsByUserId(data.getId());
                if (!CollectionUtils.isEmpty(systemIds)) {
                    List<String> list = new ArrayList<>(systemIds.size());
                    systemIds.forEach(item -> {
                        list.add("" + item);
                    });
                    data.setSystemIds(list);
                }
            } else {
                List<String> list = new ArrayList<>(1);
                list.add("0");
                data.setSystemIds(list);
            }
            return ResponseResult.success(data);
        }
        return ResponseResult.success();
    }
}
